package com.iwm.qa.mdm.adapter;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.iwm.qa.mdm.R;
import com.iwm.qa.mdm.SweetAlert.SweetAlertDialog;
import com.iwm.qa.mdm.http.OkHttp;
import com.iwm.qa.mdm.model.Device;
import com.iwm.qa.mdm.utils.AttachHttpGetParams;
import com.iwm.qa.mdm.view.DeviceDetailAct;
import com.iwm.qa.mdm.view.MainActivity;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

import okhttp3.Request;

import static com.iwm.qa.mdm.config.ApiConfig.DEL_DEVICE_INFO;

/**
 * Created by zhaohaiyang on 2017/12/20.
 */

public class NormalRecyclerViewAdapter extends RecyclerView.Adapter<NormalRecyclerViewAdapter.ViewHolder> {

    private Activity mActivity;
    private Device deviceBean;

    LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

    public String TAG = "Adapter";

    public NormalRecyclerViewAdapter(Activity activity) {
        this.mActivity = activity;
    }

    public void setData(Device deviceBean) {
        this.deviceBean = deviceBean;
        notifyDataSetChanged();
    }

    /**
     * 这个方法主要生成为每个Item inflater出一个View，但是该方法返回的是一个ViewHolder。
     * 该方法把View直接封装在ViewHolder中，然后我们面向的是ViewHolder这个实例
     *
     * @param viewGroup
     * @param viewType
     * @return
     */
    //创建新View，被LayoutManager所调用
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_item, viewGroup, false);
        return new ViewHolder(view);
    }

    //主要用于适配渲染数据到View中,将数据与界面进行绑定的操作
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, int position) {
        List<Device.DataBean> data = deviceBean.getData();
        Device.DataBean dataBean = data.get(position);
        if (data != null && data.size() > 0) {
//            Device.DataBean dataBean = data.get(position);
            viewHolder.mDeviceNameTV.setText(dataBean.getDeviceName());
            viewHolder.mDeviceDeptTV.setText(dataBean.getDeviceDept());
            viewHolder.mDeviceVersionTV.setText(dataBean.getVersionType());
            viewHolder.mDeviceBelongsTV.setText(dataBean.getDeviceBelongs());
            viewHolder.imageView.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.github));
            //将position保存在itemView的Tag中，以便点击时进行获取
            viewHolder.itemView.setOnClickListener(mClickListener);
            viewHolder.itemView.setOnLongClickListener(mLongClickListener);
            viewHolder.itemView.setTag(dataBean);
        }
    }

    //获取数据的数量
    @Override
    public int getItemCount() {
        if (deviceBean == null || deviceBean.getData() == null) {
            return 0;
        }
        return deviceBean.getData().size();
    }

    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Device.DataBean dataBean = (Device.DataBean) view.getTag();

            Intent intent = new Intent(mActivity, DeviceDetailAct.class);
            intent.putExtra("DEVICE_NAME", dataBean.getDeviceName());
            intent.putExtra("DEVICE_ASSERT_NUM", dataBean.getDeviceAssetNum());
            intent.putExtra("OS_TYPE", dataBean.getOsType());
            intent.putExtra("VERSION_TYPE", dataBean.getVersionType());
            intent.putExtra("DEVICE_RESOLUTION", dataBean.getDeviceResolution());
            intent.putExtra("REMARK", dataBean.getRemark());
            intent.putExtra("DEVICE_DEPT", dataBean.getDeviceDept());
            intent.putExtra("DEVICE_BELONGS", dataBean.getDeviceBelongs());
            mActivity.startActivity(intent);
        }
    };

    private View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            Device.DataBean dataBean = (Device.DataBean) view.getTag();
            final String delPar = dataBean.getDeviceName();
            new SweetAlertDialog(mActivity, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("Are you sure?")
                    .setContentText("Won't be able to recover this device!")
                    .setCancelText("No,cancel plx!")
                    .setConfirmText("Yes,delete it!")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            // reuse previous dialog instance, keep widget user state, reset them if you need
                            sDialog.setTitleText("Cancelled!")
                                    .setContentText("The specified device is safe :)")
                                    .setConfirmText("OK")
                                    .showCancelButton(false)
                                    .setCancelClickListener(null)
                                    .setConfirmClickListener(null)
                                    .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                        }
                    })
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            setDelDeviceOkHttp(delPar);
                            sDialog.setTitleText("Deleted!")
                                    .setContentText("The specified device has been deleted!")
                                    .setConfirmText("OK")
                                    .showCancelButton(false)
                                    .setCancelClickListener(null)
                                    .setConfirmClickListener(null)
                                    .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                        }
                    })
                    .show();
            //返回true 表示消耗了事件 事件不会继续传递
            return true;
        }
    };

    //自定义的ViewHolder，持有每个Item的所有界面元素
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mDeviceNameTV, mDeviceDeptTV, mDeviceVersionTV, mDeviceBelongsTV;
        private ImageView imageView;

        public ViewHolder(View view) {
            super(view);
            imageView = (ImageView) view.findViewById(R.id.device_photo);
            mDeviceNameTV = (TextView) view.findViewById(R.id.device_name_text);
            mDeviceDeptTV = (TextView) view.findViewById(R.id.dep_text);
            mDeviceVersionTV = (TextView) view.findViewById(R.id.version_text);
            mDeviceBelongsTV = (TextView) view.findViewById(R.id.belongs_text);
        }
    }

    private void setDelDeviceOkHttp(String parameter) {
        linkedHashMap.put("deviceName", parameter);
        String reuqestDelDeviceURL = AttachHttpGetParams.attachHttpGetParams(DEL_DEVICE_INFO, linkedHashMap);
        Log.d(TAG, reuqestDelDeviceURL);
        OkHttp.getAsync(reuqestDelDeviceURL, new OkHttp.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {
                Log.d(TAG, "requestFailure: Del device 接口请求失败");
            }

            @Override
            public void requestSuccess(String result) throws Exception {
                Log.d(TAG, "requestSuccess: Del device 接口请求成功");
                if (mActivity instanceof MainActivity) {
                    ((MainActivity) mActivity).setOkHttp();
                }
            }
        });
    }
}
